package pl.uz.zgora.plan;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SubjectNotesActivity extends Activity{

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    setContentView(R.layout.subject_notes);
	    
	    final Bundle intentParams = getIntent().getExtras();
	    final String notes = intentParams.getString("uwagi");
	    final TextView tv = (TextView) findViewById(R.id.notesField);
	    tv.setText(notes);
	    
	    
	    final PlanUzDataSource ds = new PlanUzDataSource(this);
	    final ArrayList<KalendarzTyp> calendarTypes = ds.getCalendarsTypeList();
	    Thread handleActivity = new Thread(new Runnable() {
			
			public void run() {
				for(KalendarzTyp kt: calendarTypes) {
					
					String[] calNameArray = notes.split("//");
					
					if(notes.matches(".*Dzienne.*")) {
						calNameArray = notes.split(" -");
					}
					
					String calName = calNameArray[0];
			    	if(notes.matches(kt.getNazwa() + ".*")) {
			    		ArrayList<Dzien> calendar = null;
			    		// Obsługa P i N
						try {
							String calType = calName.substring(calName.length() - 1);
							if(calType.equals("P") || calType.equals("N")) {
								calendar = ds.getCalendar(kt.getLink(), calType);
								Collections.sort(calendar, Dzien.getComparator());
							} else {
								calendar = ds.getCalendar(kt.getLink());
								Collections.sort(calendar, Dzien.getComparator());
							}
							manageCalendarUI(calendar);
						} catch (ParseException e) {
							HelperMethodsManager.manageException("onCreate()", e.getLocalizedMessage(), SubjectNotesActivity.this);
						}
						
			    		break;
			    	}
			    }
			}
		}); 
	    handleActivity.start();
	}
	
	private void manageCalendarUI(final ArrayList<Dzien> calendar) {
		final String[] items = new String[calendar.size()];
		for(int i = 0; i < calendar.size(); i++) {
			items[i] = calendar.get(i).getTydzien().replaceAll("(\\r|\\n)", "")
					+ " " + calendar.get(i).getData().replaceAll("(\\r|\\n)", "");
		}
		
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

		final ListView lv = (ListView) findViewById(R.id.subject_notes_calendar_days);
		lv.post(new Runnable() {

			public void run() {
				lv.setAdapter(adapter);
				lv.invalidateViews();
			}
		});
	}
}
